package com.superme.controller;

import com.superme.entity.PersonEntity;
import com.superme.service.ExampleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;


/**
 * Created by Administrator on 2018/1/19.
 * 用REST-API方式提供PERSON的增删改查方法
 * 200 OK - [GET]：服务器成功返回用户请求的数据，该操作是幂等的（Idempotent）。
 201 CREATED - [POST/PUT/PATCH]：用户新建或修改数据成功。
 202 Accepted - [*]：表示一个请求已经进入后台排队（异步任务）
 204 NO CONTENT - [DELETE]：用户删除数据成功。
 400 INVALID REQUEST - [POST/PUT/PATCH]：用户发出的请求有错误，服务器没有进行新建或修改数据的操作，该操作是幂等的。
 401 Unauthorized - [*]：表示用户没有权限（令牌、用户名、密码错误）。
 403 Forbidden - [*] 表示用户得到授权（与401错误相对），但是访问是被禁止的。
 404 NOT FOUND - [*]：用户发出的请求针对的是不存在的记录，服务器没有进行操作，该操作是幂等的。
 406 Not Acceptable - [GET]：用户请求的格式不可得（比如用户请求JSON格式，但是只有XML格式）。
 410 Gone -[GET]：用户请求的资源被永久删除，且不会再得到的。
 422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时，发生一个验证错误。
 500 INTERNAL SERVER ERROR - [*]：服务器发生错误，用户将无法判断发出的请求是否成功。

 GET /collection：返回资源对象的列表（数组）
 GET /collection/resource：返回单个资源对象
 POST /collection：返回新生成的资源对象
 PUT /collection/resource：返回完整的资源对象
 PATCH /collection/resource：返回完整的资源对象
 DELETE /collection/resource：返回一个空文档

 具体的restful风格可参考
 http://www.ruanyifeng.com/blog/2014/05/restful_api.html
 */
@Api(description = "人员接口")
@RestController
@RequestMapping("/api/v1")
//http://api.domian.com/v1/objects
public class ExampleController {

    @Autowired
    ExampleService es;


    //http://localhost:8080/api/v1/persons/1
    //http://localhost:8080/api/v1/persons/1/children 查子表
    //http://localhost:8080/api/v1/persons/1/children/1 查子表子记录
    @ApiOperation(value = "获取人员信息" ,  notes="获取人员信息。  </br> " +
            "例如：http://localhost:8080/api/v1/persons/1   </br> " +
            "查询子表：http://localhost:8080/api/v1/persons/1/children    </br> " +
            "查询字表详细信息：http://localhost:8080/api/v1/persons/1/children/1")
    @RequestMapping(value = "/persons/{personid}",method = RequestMethod.GET)
    @ResponseBody
    public PersonEntity getPerson(@PathVariable int personid) {
       return es.findByID(personid);
    }

    //http://localhost:8080/api/v1/persons?name=&nickname=&page=0&per_page=10&sortby=name&order=asc
    //另外一种写法 http://localhost:8080/api/v1/persons/shenm/sm/0/10/name/asc PHP代码中使用较多
    @ApiOperation(value = "根据条件获取人员信息" ,  notes="根据条件获取人员信息。" +
            "例如：http://localhost:8080/api/v1/persons?name=&nickname=&page=0&per_page=10&sortby=name&order=asc " )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "人员名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "nickname", value = "人员别名", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "需要显示第几页，第一页为0", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "per_page", value = "每页显示多少行", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "order", value = "顺序还是逆序 如：asc 或者desc", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sortby", value = "需要排序的字段", required = false, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/persons",method = RequestMethod.GET)
    @ResponseBody
    public Page<PersonEntity> getPersonByCondition(
            @RequestParam(value = "name") String name, @RequestParam(value = "nickname") String nickName, @RequestParam(value = "page") Integer pageNum,
            @RequestParam(value = "per_page") Integer pageSize, @RequestParam(value = "order") String sortDire
            ,@RequestParam(value = "sortby") String orderProprtties
            ) {
        Sort.Direction sd = Sort.Direction.ASC;
        if(sortDire.toLowerCase() == "desc")
        {
            sd=Sort.Direction.DESC;
        }
        return es.findallByCondition( name,  nickName,  pageNum,  pageSize,  sd, orderProprtties);
    }







    // http://localhost:8080/api/v1/persons POST
    /*body:
    name:AlexS
    nickname:alex
    age:30
    date:1988-10-01
    height:175
    返回新增对象
     */
    /*
    @RequestMapping(value = "/persons",method = RequestMethod.POST)
    @ResponseBody
    public boolean addPerson(@RequestParam(value = "name") String name, @RequestParam(value = "nickname") String nickName, @RequestParam(value = "age") Integer age,
                             @RequestParam(value = "date") String date, @RequestParam(value = "height") Integer height ){
        return es.AddPerson(name,nickName,age,date,height);
}
*/

    //http://localhost:8080/api/v1/persons POST
    /*body  raw json:
        {"name":"AlexSSS11223344",
        "nickname":"alex",
        "age":30,
        "birthday":"1988-10-01",
        "height":175
         }
    返回更新对象
    ajax调用方法：
    $.ajax({
            url:"/api/persons",
            type:"POST",
            dataType:"json",
            async:false,
            data:{
               "name":"AlexSSS11223344",
                "nickname":"alex",
                "age":30,
                "birthday":"1988-10-01",
                "height":175
            },
            success:function(data){
                if("201"==data.code)
                {
                    alert(data.data);
                }else{
                    alert(data.code);
                }
            },
        });
     */

    @ApiOperation(value = "新增人员信息" ,  notes="新增人员信息。<br/>" +
            "ajax调用方法：<br/>" +
            " $.ajax({<br/>" +
            "            url:\"/api/v1/persons\",<br/>" +
            "            type:\"POST\",<br/>" +
            "            dataType:\"json\",<br/>" +
            "            async:false,<br/>" +
            "            data:{<br/>" +
            "               \"name\":\"AlexSSS11223344\",<br/>" +
            "                \"nickname\":\"alex\",<br/>" +
            "                \"age\":30,<br/>" +
            "                \"birthday\":\"1988-10-01\",<br/>" +
            "                \"height\":175<br/>" +
            "            },<br/>" +
            "            success:function(data){<br/>" +
            "                if(\"201\"==data.code)<br/>" +
            "                {<br/>" +
            "                    alert(data.data);<br/>" +
            "                }else{<br/>" +
            "                    alert(data.code);<br/>" +
            "                }<br/>" +
            "            },<br/>" +
            "        });" )
    @RequestMapping(value = "/persons",method = RequestMethod.POST)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.CREATED)
    public PersonEntity addPerson(@RequestBody PersonEntity personEntity  ) throws UnsupportedEncodingException {
        String name =URLDecoder.decode(personEntity.getName(), "UTF-8");
        String nickname = URLDecoder.decode(personEntity.getNickname(), "UTF-8");
        return es.addPerson(name,nickname,personEntity.getAge(),personEntity.getBirthday(),personEntity.getHeight());
    }

    //http://localhost:8080/api/v1/persons/4 PUT
    /*body  raw json:
        {"name":"AlexSSS11223344",
        "nickname":"alex",
        "age":30,
        "birthday":"1988-10-01",
        "height":175
         }
    返回更新对象
     */

    @ApiOperation(value = "更新人员信息" ,  notes="更新人员信息。"     +
            "ajax调用方法：<br/>" +
            " $.ajax({<br/>" +
            "            url:\"/api/v1/persons/1\",<br/>" +
            "            type:\"PUT\",<br/>" +
            "            dataType:\"json\",<br/>" +
            "            async:false,<br/>" +
            "            data:{<br/>" +
            "                \"id\":1,<br/>" +
            "               \"name\":\"AlexSSS11223344\",<br/>" +
            "                \"nickname\":\"alex\",<br/>" +
            "                \"age\":30,<br/>" +
            "                \"birthday\":\"1988-10-01\",<br/>" +
            "                \"height\":175<br/>" +
            "            },<br/>" +
            "            success:function(data){<br/>" +
            "                if(\"201\"==data.code)<br/>" +
            "                {<br/>" +
            "                    alert(data.data);<br/>" +
            "                }else{<br/>" +
            "                    alert(data.code);<br/>" +
            "                }<br/>" +
            "            },<br/>" +
            "        });" )
    @RequestMapping(value = "/persons/{personid}",method = RequestMethod.PUT)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.CREATED)
    public  PersonEntity updatePerson(@PathVariable int personid,@RequestBody PersonEntity personEntity  ) throws UnsupportedEncodingException {
        String name =URLDecoder.decode(personEntity.getName(), "UTF-8");
        String nickname = URLDecoder.decode(personEntity.getNickname(), "UTF-8");
        return es.savePerson(personid,name,nickname,personEntity.getAge(),personEntity.getBirthday(),personEntity.getHeight());
    }


    @ApiOperation(value = "根据人员id删除人员信息" ,  notes="根据人员id删除人员信息。")
    //http://localhost:8080/api/v1/person/3
    @RequestMapping(value = "/persons/{personid}",method = RequestMethod.DELETE)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public boolean deletePerson(@PathVariable int personid) {
        return es.deletePerson(personid);
    }



}
